package com.lilihub.miaosha.rabbitmq;

import com.lilihub.miaosha.service.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @BelongsProject: miaosha
 * @BelongsPackage: com.lilihub.miaosha.rabbitmq
 * @Author: LiYing
 * @CreateTime: 2021-04-28 20:15
 * @Description:
 */
@Service
public class MQSender {


    @Autowired
    private AmqpTemplate amqpTemplate;

    private static Logger log = LoggerFactory.getLogger(MQRevicer.class);

    public void send(Object message){

        String msg = RedisService.beanToString(message);

        log.info("send message :" + msg);

        amqpTemplate.convertAndSend(MQConfig.QUEUE,msg);

    }



    public void sendTopic(Object message){

        String msg = RedisService.beanToString(message);

        log.info("send topic message :" + msg);

        amqpTemplate.convertAndSend(MQConfig.TOPIC_EXCHANGE,MQConfig.ROUTINGKEY1,msg + "1");
        amqpTemplate.convertAndSend(MQConfig.TOPIC_EXCHANGE,MQConfig.ROUTINGKEY2,msg + "2");

    }

    public void sendFanout(Object message){

        String msg = RedisService.beanToString(message);

        log.info("send fanout message :" + msg);

        amqpTemplate.convertAndSend(MQConfig.FANOUT_EXCHANGE,"",msg);

    }


    public void sendHeaders(Object message){

        String msg = RedisService.beanToString(message);

        log.info("send headers message :" + msg);

        MessageProperties headers = new MessageProperties();
        headers.setHeader("head1", "value1");
        headers.setHeader("head2", "value2");

        Message obj = new Message(msg.getBytes(),headers);

        amqpTemplate.convertAndSend(MQConfig.HEADERS_EXCHANGE,"",obj);

    }

    // 3 请求入队，立即返回排队中
    public void sendMiaoshaMessage(MiaoshaMessage msg) {

        String mm = RedisService.beanToString(msg);

        log.info("send message :" + mm);

        amqpTemplate.convertAndSend(MQConfig.MIAOSHA_QUEUE,mm);

    }




}
